<template>
	<view class="container">
		<!-- 页面标题 -->
		<view class="page-header">
			<text class="page-title">统计分析</text>
		</view>

		<!-- 加载状态 -->
		<view v-if="loading" class="loading-container">
			<text class="loading-text">正在加载数据...</text>
		</view>

		<!-- 错误状态 -->
		<view v-else-if="error" class="error-container">
			<text class="error-title">加载失败</text>
			<text class="error-message">{{ error }}</text>
			<view class="retry-btn" @click="loadRecords">
				<text>重试</text>
			</view>
		</view>

		<!-- 无数据状态 -->
		<view v-else-if="records.length === 0" class="empty-container">
			<text class="empty-title">暂无数据</text>
			<text class="empty-message">请先添加一些工程记录</text>
		</view>

		<!-- 主要内容 -->
		<view v-else>
			<!-- 时间筛选 -->
			<view class="filter-section">
				<view class="time-filter">
					<view class="filter-btn" :class="{ active: timeRange === 'week' }" @click="setTimeRange('week')">
						<text>本周</text>
					</view>
					<view class="filter-btn" :class="{ active: timeRange === 'month' }" @click="setTimeRange('month')">
						<text>本月</text>
					</view>
					<view class="filter-btn" :class="{ active: timeRange === 'year' }" @click="setTimeRange('year')">
						<text>本年</text>
					</view>
					<view class="filter-btn" :class="{ active: timeRange === 'all' }" @click="setTimeRange('all')">
						<text>全部</text>
					</view>
				</view>
			</view>

			<!-- 总览卡片 -->
			<view class="overview-card">
				<view class="overview-item">
					<text class="overview-label">总工程款</text>
					<text class="overview-amount income">¥{{ totalIncome.toFixed(2) }}</text>
				</view>
				<view class="overview-item">
					<text class="overview-label">已结清</text>
					<text class="overview-amount income">¥{{ totalPaid.toFixed(2) }}</text>
				</view>
				<view class="overview-item">
					<text class="overview-label">未结清</text>
					<text class="overview-amount expense">
						¥{{ totalUnpaid.toFixed(2) }}
					</text>
				</view>
			</view>

			<!-- 调试信息 -->
			<view class="debug-info">
				<text class="debug-title">调试信息：</text>
				<text class="debug-text">记录数量：{{ records.length }}</text>
				<text class="debug-text">筛选后数量：{{ filteredRecords.length }}</text>
				<text class="debug-text">时间范围：{{ timeRange }}</text>
			</view>



			<!-- 付款状态统计 -->
			<view class="stats-section">
				<text class="section-title">付款状态统计</text>
				<view class="status-stats">
					<view class="status-item">
						<view class="status-info">
							<view class="status-icon paid">✓</view>
							<text class="status-text">已结清</text>
							<text class="status-count">{{ paidCount }}个</text>
						</view>
						<text class="status-amount">¥{{ totalPaid.toFixed(2) }}</text>
					</view>
					<view class="status-item">
						<view class="status-info">
							<view class="status-icon partial">⚠</view>
							<text class="status-text">部分付款</text>
							<text class="status-count">{{ partialCount }}个</text>
						</view>
						<text class="status-amount">¥{{ totalPartial.toFixed(2) }}</text>
					</view>
					<view class="status-item">
						<view class="status-info">
							<view class="status-icon unpaid">✗</view>
							<text class="status-text">未付款</text>
							<text class="status-count">{{ unpaidCount }}个</text>
						</view>
						<text class="status-amount">¥{{ totalUnpaid.toFixed(2) }}</text>
					</view>
				</view>
			</view>

			<!-- 项目列表 -->
			<view class="stats-section">
				<text class="section-title">项目列表</text>
				<view class="project-list">
					<view v-for="record in filteredRecords" :key="record.id" class="project-item">
						<text class="project-name">{{ record.id }}</text>
						<text class="project-amount">¥{{ record.amount.toFixed(2) }}</text>
						<text class="project-status" :class="record.status">{{ getStatusText(record.status) }}</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import { 
	calculateTotalUnpaidAmount, 
	calculateTotalPaidAmount, 
	calculateTotalAmount,
	getStatusText 
} from '../../utils/calculations.js'

export default {
	data() {
		return {
			timeRange: 'all',
			records: [],
			loading: true,
			error: null
		}
	},
	computed: {
		filteredRecords() {
			try {
				if (this.timeRange === 'all') {
					return this.records
				}
				
				const now = new Date()
				const startDate = new Date()
				
				switch (this.timeRange) {
					case 'week':
						// 本周：从本周一开始
						const dayOfWeek = now.getDay()
						const daysFromMonday = dayOfWeek === 0 ? 6 : dayOfWeek - 1
						startDate.setDate(now.getDate() - daysFromMonday)
						startDate.setHours(0, 0, 0, 0)
						break
					case 'month':
						// 本月：从本月1号开始
						startDate.setDate(1)
						startDate.setHours(0, 0, 0, 0)
						break
					case 'year':
						// 本年：从今年1月1号开始
						startDate.setMonth(0, 1)
						startDate.setHours(0, 0, 0, 0)
						break
				}
				
				console.log(`时间筛选: ${this.timeRange}, 开始时间: ${startDate.toISOString()}, 结束时间: ${now.toISOString()}`)
				
				return this.records.filter(record => {
					if (!record.createTime) {
						console.warn(`记录 ${record.id} 缺少创建时间，跳过时间筛选`)
						return false
					}
					
					try {
						const recordDate = new Date(record.createTime)
						if (isNaN(recordDate.getTime())) {
							console.warn(`记录 ${record.id} 的创建时间格式无效: ${record.createTime}`)
							return false
						}
						
						const isInRange = recordDate >= startDate && recordDate <= now
						if (isInRange) {
							console.log(`记录 ${record.id} 在时间范围内: ${recordDate.toISOString()}`)
						}
						
						return isInRange
					} catch (error) {
						console.error(`解析记录 ${record.id} 的创建时间失败:`, error)
						return false
					}
				})
			} catch (error) {
				console.error('筛选记录失败:', error)
				return this.records
			}
		},
		totalIncome() {
			try {
				// 总工程款：所有工程的总金额
				return this.filteredRecords.reduce((sum, record) => {
					return sum + (record.amount || 0)
				}, 0)
			} catch (error) {
				console.error('计算总收入失败:', error)
				return 0
			}
		},
		totalPaid() {
			try {
				// 已结清：状态为 'paid' 的工程总金额
				return this.filteredRecords
					.filter(record => record.status === 'paid')
					.reduce((sum, record) => {
						return sum + (record.amount || 0)
					}, 0)
			} catch (error) {
				console.error('计算已付款失败:', error)
				return 0
			}
		},
		totalPartial() {
			try {
				// 部分付款：状态为 'partial' 的工程已付款金额
				const partialRecords = this.filteredRecords.filter(record => record.status === 'partial')
				return partialRecords.reduce((sum, record) => {
					// 从付款记录中获取实际已付款金额
					const payments = uni.getStorageSync('project_payments') || []
					const projectPayments = payments.filter(p => p.projectId === record.id)
					const totalPaid = projectPayments.reduce((paidSum, p) => paidSum + (p.amount || 0), 0)
					return sum + totalPaid
				}, 0)
			} catch (error) {
				console.error('计算部分付款失败:', error)
				return 0
			}
		},
		totalUnpaid() {
			try {
				// 未结清：状态为 'unpaid' 和 'partial' 的工程未付款金额
				const unpaidRecords = this.filteredRecords.filter(record => 
					record.status === 'unpaid' || record.status === 'partial'
				)
				return unpaidRecords.reduce((sum, record) => {
					if (record.status === 'unpaid') {
						// 未付款：返回工程总金额
						return sum + (record.amount || 0)
					} else if (record.status === 'partial') {
						// 部分付款：返回剩余未付款金额
						const payments = uni.getStorageSync('project_payments') || []
						const projectPayments = payments.filter(p => p.projectId === record.id)
						const totalPaid = projectPayments.reduce((paidSum, p) => paidSum + (p.amount || 0), 0)
						const remainingAmount = Math.max(0, (record.amount || 0) - totalPaid)
						return sum + remainingAmount
					}
					return sum
				}, 0)
							} catch (error) {
					console.error('计算未付款失败:', error)
					return 0
				}
			},
		paidCount() {
			try {
				return this.filteredRecords.filter(record => record.status === 'paid').length
			} catch (error) {
				console.error('计算已付款数量失败:', error)
				return 0
			}
		},
		partialCount() {
			try {
				return this.filteredRecords.filter(record => record.status === 'partial').length
			} catch (error) {
				console.error('计算部分付款数量失败:', error)
				return 0
			}
		},
		unpaidCount() {
			try {
				return this.filteredRecords.filter(record => record.status === 'unpaid').length
			} catch (error) {
				console.error('计算未付款数量失败:', error)
				return 0
			}
		}
	},
	onLoad() {
		console.log('统计分析页面加载')
		this.loadRecords()
	},
	onShow() {
		console.log('统计分析页面显示')
		this.loadRecords()
	},
	methods: {
		loadRecords() {
			this.loading = true
			this.error = null
			
			try {
				console.log('开始加载数据...')
				
				// 获取工程数据
				const projects = uni.getStorageSync('engineering_projects') || []
				console.log('加载项目数据:', projects.length, '个项目')
				
				// 验证数据格式
				if (!Array.isArray(projects)) {
					throw new Error('项目数据格式错误')
				}
				
				// 获取付款数据
				const payments = uni.getStorageSync('project_payments') || []
				if (!Array.isArray(payments)) {
					console.warn('付款数据格式错误，已重置为空数组')
					uni.setStorageSync('project_payments', [])
				}
				
				// 处理数据并同步状态
				this.records = projects.map(project => {
					// 确保必要字段存在
					const record = {
						id: project.id || '未知项目',
						amount: parseFloat(project.totalAmount) || 0,
						createTime: project.createTime || project.createDate || project.date || null,
						status: project.status || 'unpaid'
					}
					
					// 验证金额
					if (isNaN(record.amount) || record.amount < 0) {
						record.amount = 0
					}
					
					// 如果没有创建时间，使用项目ID作为标识（避免时间筛选问题）
					if (!record.createTime) {
						console.warn(`项目 ${record.id} 缺少创建时间，将使用默认时间`)
						record.createTime = '2024-01-01T00:00:00.000Z' // 使用固定默认时间
					}
					
					// 同步付款状态
					record.status = this.syncProjectStatus(record, payments)
					
					return record
				})
				
				console.log('处理后的记录:', this.records.length, '条记录')
				
				// 验证数据一致性
				this.validateDataConsistency()
				
				// 验证时间数据
				this.validateTimeData()
				
				this.loading = false
				
			} catch (error) {
				console.error('加载数据失败:', error)
				this.error = error.message || '加载数据失败'
				this.loading = false
				
				uni.showToast({
					title: '加载数据失败',
					icon: 'none'
				})
			}
		},
		setTimeRange(range) {
			console.log('设置时间范围:', range)
			this.timeRange = range
		},
		getStatusText(status) {
			const statusMap = {
				'unpaid': '未付款',
				'partial': '部分付款',
				'paid': '已结清'
			}
			return statusMap[status] || '未知'
		},
		syncProjectStatus(project, payments) {
			// 根据付款记录同步项目状态，确保数据一致性
			const projectPayments = payments.filter(p => p.projectId === project.id)
			const totalPaid = projectPayments.reduce((sum, p) => sum + (p.amount || 0), 0)
			const totalAmount = project.amount || 0
			
			// 使用精确的数值比较，避免浮点数精度问题
			const epsilon = 0.01 // 允许的误差范围
			
			if (totalAmount <= 0) {
				return 'unpaid' // 金额为0或负数时设为未付款
			} else if (Math.abs(totalPaid - totalAmount) <= epsilon) {
				return 'paid' // 已付款金额与总金额相等（允许误差）
			} else if (totalPaid > epsilon) {
				return 'partial' // 已付款但未完全付清
			} else {
				return 'unpaid' // 未付款
			}
		},
		validateDataConsistency() {
			// 验证数据一致性，确保计算的数据与实际数据对应
			console.log('=== 数据一致性验证 ===')
			
			// 获取所有付款记录
			const payments = uni.getStorageSync('project_payments') || []
			
			// 计算实际的已付款总额
			const actualTotalPaid = payments.reduce((sum, p) => sum + (p.amount || 0), 0)
			
			// 计算实际的工程总金额
			const actualTotalAmount = this.records.reduce((sum, record) => sum + (record.amount || 0), 0)
			
			// 计算实际的未付款总额
			const actualTotalUnpaid = actualTotalAmount - actualTotalPaid
			
			console.log('实际工程总金额:', actualTotalAmount)
			console.log('实际已付款总额:', actualTotalPaid)
			console.log('实际未付款总额:', actualTotalUnpaid)
			console.log('计算的总收入:', this.totalIncome)
			console.log('计算的已付款:', this.totalPaid)
			console.log('计算的未付款:', this.totalUnpaid)
			
			// 验证计算是否正确
			const incomeDiff = Math.abs(actualTotalAmount - this.totalIncome)
			const paidDiff = Math.abs(actualTotalPaid - this.totalPaid)
			const unpaidDiff = Math.abs(actualTotalUnpaid - this.totalUnpaid)
			
			if (incomeDiff > 0.01) {
				console.warn('总收入计算错误，差值:', incomeDiff)
			}
			if (paidDiff > 0.01) {
				console.warn('已付款计算错误，差值:', paidDiff)
			}
			if (unpaidDiff > 0.01) {
				console.warn('未付款计算错误，差值:', unpaidDiff)
			}
			
			if (incomeDiff <= 0.01 && paidDiff <= 0.01 && unpaidDiff <= 0.01) {
				console.log('✓ 数据一致性验证通过')
			} else {
				console.error('✗ 数据一致性验证失败')
			}
		},
		validateTimeData() {
			// 验证时间数据的有效性
			console.log('=== 时间数据验证 ===')
			
			const timeIssues = []
			const validRecords = []
			
			this.records.forEach(record => {
				if (!record.createTime) {
					timeIssues.push({
						id: record.id,
						issue: '缺少创建时间',
						value: record.createTime
					})
				} else {
					try {
						const recordDate = new Date(record.createTime)
						if (isNaN(recordDate.getTime())) {
							timeIssues.push({
								id: record.id,
								issue: '创建时间格式无效',
								value: record.createTime
							})
						} else {
							validRecords.push({
								id: record.id,
								time: recordDate.toISOString(),
								formatted: recordDate.toLocaleDateString('zh-CN')
							})
						}
					} catch (error) {
						timeIssues.push({
							id: record.id,
							issue: '创建时间解析失败',
							value: record.createTime,
							error: error.message
						})
					}
				}
			})
			
			console.log('有效时间记录:', validRecords.length)
			validRecords.slice(0, 5).forEach(record => {
				console.log(`  ${record.id}: ${record.formatted} (${record.time})`)
			})
			
			if (timeIssues.length > 0) {
				console.warn('时间数据问题:', timeIssues.length)
				timeIssues.forEach(issue => {
					console.warn(`  ${issue.id}: ${issue.issue} - ${issue.value}`)
				})
			} else {
				console.log('✓ 所有记录都有有效的时间数据')
			}
			
			// 显示时间范围信息
			if (validRecords.length > 0) {
				const times = validRecords.map(r => new Date(r.time))
				const earliest = new Date(Math.min(...times))
				const latest = new Date(Math.max(...times))
				console.log(`时间范围: ${earliest.toLocaleDateString('zh-CN')} 到 ${latest.toLocaleDateString('zh-CN')}`)
			}
		}
	}
}
</script>

<style scoped>
.container {
	background-color: #f5f5f5;
	min-height: 100vh;
	padding: 20rpx;
}

.page-header {
	text-align: center;
	padding: 40rpx 0;
}

.page-title {
	font-size: 36rpx;
	font-weight: bold;
	color: #333;
}

/* 加载状态样式 */
.loading-container {
	display: flex;
	justify-content: center;
	align-items: center;
	padding: 100rpx 0;
}

.loading-text {
	font-size: 28rpx;
	color: #666;
}

/* 错误状态样式 */
.error-container {
	background: white;
	border-radius: 20rpx;
	padding: 40rpx;
	margin: 20rpx 0;
	text-align: center;
}

.error-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #f44336;
	display: block;
	margin-bottom: 20rpx;
}

.error-message {
	font-size: 28rpx;
	color: #666;
	display: block;
	margin-bottom: 30rpx;
}

.retry-btn {
	background: #667eea;
	color: white;
	padding: 20rpx 40rpx;
	border-radius: 10rpx;
	display: inline-block;
}

/* 空数据状态样式 */
.empty-container {
	background: white;
	border-radius: 20rpx;
	padding: 80rpx 40rpx;
	margin: 20rpx 0;
	text-align: center;
}

.empty-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #666;
	display: block;
	margin-bottom: 20rpx;
}

.empty-message {
	font-size: 28rpx;
	color: #999;
	display: block;
}

.filter-section {
	background: white;
	border-radius: 20rpx;
	padding: 20rpx;
	margin-bottom: 20rpx;
}

.time-filter {
	display: flex;
	background: #f5f5f5;
	border-radius: 15rpx;
	padding: 5rpx;
}

.filter-btn {
	flex: 1;
	text-align: center;
	padding: 20rpx;
	border-radius: 10rpx;
	transition: all 0.3s;
}

.filter-btn.active {
	background: white;
	color: #667eea;
	font-weight: bold;
}

.overview-card {
	background: white;
	border-radius: 20rpx;
	padding: 30rpx;
	margin-bottom: 20rpx;
	display: flex;
	justify-content: space-between;
}

.overview-item {
	text-align: center;
	flex: 1;
}

.overview-label {
	font-size: 24rpx;
	color: #666;
	display: block;
	margin-bottom: 10rpx;
}

.overview-amount {
	font-size: 32rpx;
	font-weight: bold;
	display: block;
}

.income {
	color: #4CAF50;
}

.expense {
	color: #F44336;
}

.debug-info {
	background: white;
	padding: 20rpx;
	margin-bottom: 20rpx;
	border-radius: 10rpx;
}

.debug-title {
	font-size: 28rpx;
	font-weight: bold;
	color: #333;
	display: block;
	margin-bottom: 10rpx;
}

.debug-text {
	font-size: 24rpx;
	color: #666;
	display: block;
	margin-bottom: 5rpx;
}



.stats-section {
	background: white;
	border-radius: 20rpx;
	padding: 30rpx;
	margin-bottom: 20rpx;
}

.section-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 30rpx;
	display: block;
}

.status-stats {
	display: flex;
	flex-direction: column;
	gap: 20rpx;
}

.status-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20rpx;
	background: #f8f9fa;
	border-radius: 12rpx;
}

.status-info {
	display: flex;
	align-items: center;
	gap: 15rpx;
}

.status-icon {
	width: 40rpx;
	height: 40rpx;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 20rpx;
	color: white;
	font-weight: bold;
}

.status-icon.paid {
	background: #4CAF50;
}

.status-icon.partial {
	background: #FF9800;
}

.status-icon.unpaid {
	background: #F44336;
}

.status-text {
	font-size: 28rpx;
	color: #333;
	font-weight: bold;
}

.status-count {
	font-size: 24rpx;
	color: #666;
}

.status-amount {
	font-size: 28rpx;
	font-weight: bold;
	color: #333;
}

.project-list {
	display: flex;
	flex-direction: column;
	gap: 15rpx;
}

.project-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20rpx;
	background: #f8f9fa;
	border-radius: 12rpx;
}

.project-name {
	font-size: 28rpx;
	color: #333;
	font-weight: bold;
}

.project-amount {
	font-size: 28rpx;
	color: #667eea;
	font-weight: bold;
}

.project-status {
	padding: 6rpx 12rpx;
	border-radius: 12rpx;
	font-size: 22rpx;
	color: white;
}

.project-status.unpaid {
	background: #ff4757;
}

.project-status.partial {
	background: #ffa502;
}

.project-status.paid {
	background: #2ed573;
}
</style>
